const express = require('express');
const cors = require('cors');
const convertRouter = require('./routes/convert');
const path = require('path');
const os = require('os');

const app = express();
const PORT = process.env.PORT || 3000;

// 获取本机 IP 地址
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  const addresses = [];

  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      // 只获取 IPv4 地址
      if (iface.family === 'IPv4' && !iface.internal) {
        addresses.push(iface.address);
      }
    }
  }

  // 返回第一个找到的地址，如果没有则返回 localhost
  return addresses[0] || 'localhost';
}

const localIP = getLocalIP();

// 设置请求超时
app.use((req, res, next) => {
  req.setTimeout(300000); // 5分钟超时
  res.setTimeout(300000);
  next();
});

// 增加文件大小限制
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));

// 修改 CORS 配置
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 86400
}));

// 添加额外的 CORS 头
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

// 静态文件服务 - 确保路径正确
const convertedDir = path.join(__dirname, '../converted');
console.log('PDF文件目录:', convertedDir);
app.use('/converted', express.static(convertedDir));

// 静态文件服务 - 添加对 public 目录的访问
app.use(express.static(path.join(__dirname, '../public')));

// 测试路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

// API路由
app.use('/api', convertRouter);

// 添加 ping 接口
app.get('/api/ping', (req, res) => {
  try {
    const ip = getLocalIP();
    res.json({ 
      success: true,
      ip: ip,
      time: Date.now()
    });
  } catch (error) {
    res.json({ 
      success: false,
      error: 'Failed to get IP'
    });
  }
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({
    success: false,
    message: '服务器错误'
  });
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`服务器运行在:`);
  console.log(`- 本地访问: http://localhost:${PORT}`);
  console.log(`- 局域网访问: http://${localIP}:${PORT}`);
  console.log(`- cpolar访问: https://48f365cb.r27.cpolar.top `);
}); //cd D:\wechat_open\project\cpolar ; ./cpolar.exe http 3000